import { useEffect } from "react"
import { QueryKey, useMutation, useQuery, useQueryClient } from "react-query"

import { useProjectSeacrchParam } from "screens/ProjectList/util"
import { Project } from "types"
import { cleanObject } from "utils"
import { useHttp } from "./http"
import { useAddConfig, useDeleteConfig, useEditConfig } from "./use-optimistic-options"
import { useAsync } from "./useAsync"

export const useProjects = (param?: Partial<Project>) => {
  const client = useHttp()
  // const {run, ...result} = useAsync<Project[]>()
  // const fetchProjects = () => client('projects',{data:cleanObject(param||{})})

  // useEffect(()=>{
  //   run(fetchProjects(),{
  //     retry:fetchProjects
  //   })
  // },[param])

  // return result

  /**
   * @react-query 使用useQuery
   */
  // return useQuery<Project[], Error>(['projects', param], () => client('projects', { data: param }))
  return useQuery<Project[]>(
    ['projects', param],
    () => client('projects', { data: param })
  )
}

export const useEditProject = (queryKey:QueryKey) => {
  const client = useHttp()
  // const {run,...asyncResult} = useAsync()
  // const mutate = (params:Partial<Project>) => {
  //  return  run(client(`projects/${params.id}`,{data:params,method:'PATCH'}))
  // }

  // return{
  //   mutate,
  //   ...asyncResult
  // }

  /**
   * @react-query 使用useQuery
   */
  // const queryClient = useQueryClient()
  // const [searchParams] = useProjectSeacrchParam()
  // const queryKey = ['project', searchParams]

  return useMutation(
    (params: Partial<Project>) => client(`projects/${params.id}`,
    {
      method: "PATCH",
      data: params
    }),
    useEditConfig(queryKey)
  ) 
  // {
  //   onSuccess: () => queryClient.invalidateQueries(queryKey),
  //   async onMutate(target) {
  //     const previousItems = queryClient.getQueryData(queryKey)
  //     queryClient.setQueryData(queryKey, (old?: Project[]) => {
  //       return old?.map(project =>
  //         project.id === target.id ?
  //           { ...project, ...target } :
  //           project
  //       ) || []
  //     })
  //     return {previousItems}
  //   },
  //   onError(error,newItem,context:any){
  //     queryClient.setQueryData(queryKey,context.previousItems)
  //     // queryClient.setQueryData(queryKey,(context as {previousItmes:Project[]}).previousItems)
  //   }
  //   }
}

export const useAddProject = (queryKey:QueryKey) => {
  const client = useHttp()
  // const { run, ...asyncResult } = useAsync()
  // const mutate = (params: Partial<Project>) => {
  //   return run(
  //     client(`projects/${params.id}`, 
  //     { data: params, method: 'POST' }))
  // }

  // return {
  //   mutate,
  //   ...asyncResult
  // }

  /**
   * 使用 useQuery
   */
  // const queryClient = useQueryClient()

  return useMutation(
    (params: Partial<Project>) =>
      client(`projects`,
        {
          method: "POST",
          data: params
        }
      ),
    useAddConfig(queryKey)
  )
}

export const useProject = (id?: number) => {
  const client = useHttp()
  return useQuery<Project>(
    ['project', { id }],
    () => client(`projects/${id}`),
    {
      enabled: Boolean(id)
    }
  )
}

export const useDeleteProject = (queryKey:QueryKey) => {
  const client = useHttp()

  return useMutation(
    (id:number) =>
      client(`projects/${id}`,
        {
          method: "DELETE",
        }
      ),
    useDeleteConfig(queryKey)
  )
}